<template>
	<view class="page-container">
		<uni-ele-search :showCount="30" inline :searchForm="searchForm" @onSearch="onSearch"></uni-ele-search>
		<view class="btns-box">
			<el-tabs v-model="activeIndex" class="tabs-box" @tab-click="tabHandleClick">
				<el-tab-pane label="安置房" name="3"></el-tab-pane>
				<el-tab-pane label="限价房" name="4"></el-tab-pane>
			</el-tabs>
			<view class="btns">
				<el-button class="btn" size="mini" @click="downloadExcel" type="danger">下载表格模板</el-button>
				<el-upload ref="uploadExcel" :action="uploadUrl" :http-request="uploadSuccess" :limit="1" :show-file-list="false" accept=".xls" class="btn upload-btn">
					上传文件
				</el-upload>
				<el-button class="btn" size="mini" type="info" @click="navToHistory">上传记录</el-button>
				<el-button class="btn" size="mini" type="primary" @click="batchDownload">批量下载</el-button>
				<el-button class="btn" size="mini"
                   type="primary"
                   @click="batchDownloadAll">
          导出全部数据
        </el-button>
			</view>
		</view>
		<uni-ele-table :columns="columns" :data="tableData" pageable @action="handleClick" @pageChange="pageChange" @selectionChange="selectionChange"></uni-ele-table>
		<el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="visble" title="上传表单确认" width="80%">
			<uni-ele-table :columns="tmpColumns" :data="tempTableData" pageable @action="handleClick" @pageChange="pageChange"></uni-ele-table>
			<div slot="footer" class="dialog-footer"><el-button size="small" type="primary" @click="confrimSubmit">确认提交</el-button></div>
		</el-dialog>

		<el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="uploadDialogVisble" title="上传附件" width="30%">
			<view class="upload-box">
				<view class="upload-item">
					<el-upload
						ref="uploadAgreement"
						:action="uploadUrl"
						:data="{ name: 'demolitionAgreement', type: 1 }"
						:http-request="uploadSuccess"
						:limit="1"
						:accept="fileAccept"
						class="btn upload-btn"
					>
						<el-button slot="trigger" size="small" type="primary">选取拆迁协议文件</el-button>
						<view v-if="currentItem.demolitionAgreement && currentItem.demolitionAgreement.length > 0">
							<text>{{ currentItem.demolitionAgreement || '' }}</text>
							<text style="padding: 0 5px;color: blue;cursor: pointer;" @click.stop="deleteAttachment(1)">删除</text>
						</view>
					</el-upload>
				</view>
				<view class="upload-item">
					<el-upload
						ref="uploadConfirm"
						:action="uploadUrl"
						:data="{ name: 'confirmSheet', type: 2 }"
						:http-request="uploadSuccess"
						:limit="1"
						:accept="fileAccept"
						class="btn upload-btn"
					>
						<el-button slot="trigger" size="small" type="primary">选取选房确认单文件</el-button>
						<view v-if="currentItem.confirmSheet && currentItem.confirmSheet.length > 0">
							<text>{{ currentItem.confirmSheet || '' }}</text>
							<text style="padding: 0 5px;color: blue;cursor: pointer;" @click.stop="deleteAttachment(2)">删除</text>
						</view>
					</el-upload>
				</view>
				<view class="upload-item">
					<el-upload
						ref="uploadContract"
						:action="uploadUrl"
						:data="{ name: 'housePurchasingContract', type: 3 }"
						:http-request="uploadSuccess"
						:limit="1"
						:accept="fileAccept"
						class="btn upload-btn"
					>
						<el-button slot="trigger" size="small" type="primary">选取购房合同文件</el-button>
						<view v-if="currentItem.housePurchasingContract && currentItem.housePurchasingContract.length > 0">
							<text>{{ currentItem.housePurchasingContract || '1' }}</text>
							<text style="padding: 0 5px;color: blue;cursor: pointer;" @click.stop="deleteAttachment(3)">删除</text>
						</view>
					</el-upload>
				</view>
			</view>
			<div slot="footer" class="dialog-footer"><el-button size="small" type="primary" @click="submitUpLoad">确认提交</el-button></div>
		</el-dialog>
    <el-drawer title="房源信息" direction="rtl" :visible.sync="showDrawer" size="50%" class="house-drawer">
      <house-view />
    </el-drawer>
	</view>
</template>

<script>
import {
	houseList,
	deleteAttachment,
	confirm,
	getStreetNameDropDownList,
	deleteById,
	confirmUploadAttachment,
	createDownLoadTask,
	downLoadExcelBatchByType
} from '@/common/services/house.js';
import HouseView from "../plugins/houseView";

export default {
  components: {HouseView},
  data() {
		return {
			fileAccept: '.png,.jpg,.jpeg,.pdf',
			uploadDialogVisble: false,
			activeIndex: '3',
			uploadUrl: 'http://localhost:8022/house/importFile',
			visble: false,
			size: 20,
			searchData: {},
			searchForm: [
				// {
				// 	title: '房屋性质',
				// 	valueType: 'select',
				// 	value: 'type',
				// 	options: [
				// 		{
				// 			name: '安置房',
				// 			value: 3
				// 		},
				// 		{
				// 			name: '限价房',
				// 			value: 4
				// 		},
				// 		{
				// 			name: '人才房',
				// 			value: 0
				// 		},
				// 		{
				// 			name: '公（廉）租房',
				// 			value: 1
				// 		},
				// 		{
				// 			name: '保租房',
				// 			value: 2
				// 		},
				// 		{
				// 			name: '共有产权房',
				// 			value: 5
				// 		}
				// 	]
				// },
				{
					title: '所属街道',
					valueType: 'select',
					value: 'streetName',
					filterable: true,
					options: []
				},
				{
					title: '小区名称',
					valueType: 'input',
					value: 'communityName'
				},
				{
					title: '选配状态',
					valueType: 'select',
					value: 'chosenStatus',
					options: [
						{
							name: '已选配',
							value: '已选配'
						},
						{
							name: '未选配',
							value: '未配租'
						}
					]
				},
				{
					title: '安置人姓名',
          valueType: 'input',
          value: 'name'
        },
        {
          title: '手机号',
          valueType: 'input',
          value: 'mobile'
        },
        {
          title: '竣工时间',
          valueType: 'daterange',
          value: 'startTimes',
          format: 'yyyy-MM-dd HH:mm:00',
          date: true
        },
        {
          title: '交付时间',
          valueType: 'daterange',
          value: 'endTimes',
          format: 'yyyy-MM-dd HH:mm:00',
          date: true
        }
      ],
			columns: [
				{
					title: '序号',
					valueType: 'selection',
					width: 50,
					align: 'center'
				},
				{
					title: '小区名称',
					dataIndex: 'communityName',
					align: 'center',
					minWidth: 80,
					style: {
						display: 'initial'
					}
				},
				{
					title: '街道',
					dataIndex: 'streetName',
					align: 'center',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '开发单位',
					dataIndex: 'companyName',
					align: 'center',
					minWidth: 120,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2,
						display: 'initial'
					}
				},
				{
					title: '竣工备案时间',
					dataIndex: 'finishFilingTime',
					align: 'center',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					},
					render: row => {
						return this.$utils.timeFormat(row.finishFilingTime);
					}
				},
				{
					title: '交付时间',
					dataIndex: 'leadTime',
					align: 'center',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					},
					render: row => {
						return this.$utils.timeFormat(row.leadTime);
					}
				},
				{
					title: '房号',
					dataIndex: 'roomNumber',
					align: 'center',
					minWidth: 60,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '面积（㎡）',
					dataIndex: 'rent',
					align: 'center',
					minWidth: 100,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					},
					render: row => {
						if (row.rent && row.rent.length > 0) {
							return parseFloat(row.rent).toFixed(2);
						}
						return '-';
					}
				},
				{
					title: '选配状态',
					dataIndex: 'chosenStatus',
					align: 'center',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '安置人准购证',
					dataIndex: 'settlerBuyPermit',
					align: 'center',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '安置人姓名',
					dataIndex: 'settlerName',
					align: 'center',
					minWidth: 100,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					},
					render: row => {
						return (row.settlerName || '') + '<br/>' + (row.settlerIdCard || '');
					}
				},
				{
					title: '手机号',
					dataIndex: 'settlerMobile',
					align: 'center',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '选房日期',
					dataIndex: 'chosenHouseTime',
					align: 'center',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					},
					render: row => {
						return this.$utils.timeFormat(row.chosenHouseTime);
					}
				},
				{
					title: '拆迁项目名称',
					dataIndex: 'demolitionProjectName',
					align: 'center',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '动迁公司',
					dataIndex: 'demolitionCompanyName',
					align: 'center',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '建设成本（元）',
					dataIndex: 'capitalCost',
					align: 'center',
					unitType: 'money',
					minWidth: 100,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '房屋价格（元）',
					dataIndex: 'houseCost',
					unitType: 'money',
					align: 'center',
					minWidth: 100,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '车位',
					dataIndex: 'carport',
					align: 'center',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '车位价格（元）',
					dataIndex: 'carportPrice',
					unitType: 'money',
					align: 'center',
					minWidth: 100,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '贮藏室',
					dataIndex: 'storeroom',
					minWidth: 80,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '贮藏室价格（元）',
					dataIndex: 'storeroomPrice',
					unitType: 'money',
					align: 'center',
					minWidth: 100,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '安置人拆迁协议',
					dataIndex: 'demolitionAgreement',
					align: 'center',
					minWidth: 120,
					render: row => {
						if (row.demolitionAgreement.indexOf('/download') >= 0) {
							return `<a target="_blank" href="${row.demolitionAgreement}"> 查看拆迁协议 </a>`;
						}
						return '';
					}
				},
				{
					title: '选房确认单',
					dataIndex: 'confirmSheet',
					align: 'center',
					minWidth: 120,
					render: row => {
						if (row.confirmSheet.indexOf('/download') >= 0) {
							return `<a target="_blank" href="${row.confirmSheet}"> 查看选房确认单 </a>`;
						}
						return '';
					}
				},
				{
					title: '购房合同',
					dataIndex: 'housePurchasingContract',
					align: 'center',
					minWidth: 120,
					render: row => {
						if (row.housePurchasingContract.indexOf('/download') >= 0) {
							return `<a target="_blank" href="${row.housePurchasingContract}"> 查看购房合同 </a>`;
						}
						return '';
					}
				},
				{
					title: '上传时间',
					dataIndex: 'createTime',
					align: 'center',
					minWidth: 100,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '备注',
					dataIndex: 'remark',
					align: 'center',
					minWidth: 150,
					style: {
						'-webkit-line-clamp': 2,
						'line-clamp': 2
					}
				},
				{
					title: '操作',
					valueType: 'action',
					fixed: 'right',
					width: 80,
					actions: [
						{
							title: '上传附件',
							type: 'upload',
							authCode: 'house:placement:delete'
						},
						{
							title: '删除',
							type: 'delete',
							authCode: 'house:placement:delete'
						},
            {
              title: '详情',
              type: 'view',
              authCode: 'house:placement:delete'
            }
					]
				}
			],
			/* table 数据 */
			tableData: {},
			tempTableData: {},
			batchNo: '',
			type: 3,
			fileUrl: [],
			currentItem: {},
			currentId: 0,
			selectedIds: [],
			pageIndex: 1,
			tmpColumns: [],
      showDrawer: false
		};
	},
	onLoad() {
		let self = this;
		this.tmpColumns = [].concat(this.columns);
		this.tmpColumns.splice(0, 1);
		this.list();
		setTimeout(() => {
			getStreetNameDropDownList().then(ret => {
				self.searchForm[0].options = ret || [];
			});
		}, 500);
	},
	methods: {
		downloadExcel() {
			if (this.type === 3) {
				window.open(`/download/安置房房源统计模板.xls`);
			} else {
				window.open(`/download/限价房房源统计模板.xls`);
			}
		},
		uploadSuccess(res) {
			let self = this;
			self.batchNo = '';
			self.$utils.loading();
			let url = `${self.$env.base}/house/importFile/${this.type}`;
			let sourceType = 0;
			if (res.data) {
				sourceType = res.data.type;
				url = `${self.$env.base}/house/importFile/attachment/${sourceType}/${this.type}`;
			}
			uni.uploadFile({
				url: url,
				file: res.file,
				name: 'file',
				header: {
					Authorization: uni.getStorageSync('token') || ''
				},
				success: ret => {
					self.$refs.uploadExcel.clearFiles();
					self.$utils.loading(true);
					let data = JSON.parse(ret.data);
					if (ret.statusCode == 200 && data.code === self.$env.successCode) {
						self.$utils.notify('文件[' + res.file.name + ']上传成功。');
						if (sourceType === 0) {
							self.batchNo = data.data;
							self.list({ batchNo: self.batchNo, confirm: 0 }, true);
						} else {
							self.fileUrl.push({
								sourceType: sourceType,
								url: data.data
							});
						}
					} else {
            self.$utils.notify('文件[' + res.file.name + ']上传失败!' + data.errMsg || '', 'error');
					}
				},
				fail: err => {
					self.$refs.uploadExcel.clearFiles();
          self.$utils.loading(true);
          self.$utils.notify('文件[' + res.file.name + ']上传失败!', 'error');
				}
			});
		},
		confrimSubmit() {
			let self = this;
			confirm(this.batchNo, this.type).then(ret => {
				self.visble = false;
				self.$utils.notify('提交成功');
				self.batchNo = '';
				self.list();
			});
		},
		submitUpLoad() {
			let self = this;
			let data = {
				id: this.currentId,
				files: this.fileUrl
			};
			confirmUploadAttachment(data).then(ret => {
				self.uploadDialogVisble = false;
				// self.onSearch();
				self.list({
					current: self.pageIndex,
					...self.searchData
				});
				self.$refs.uploadAgreement.clearFiles();
				self.$refs.uploadConfirm.clearFiles();
				self.$refs.uploadContract.clearFiles();
			});
		},
		deleteAttachment(type) {
			let self = this;
			this.$confirm('确定要删除这条附件文件吗?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				deleteAttachment(self.currentId, type).then(ret => {
					if (type === 1) {
						self.currentItem.demolitionAgreement = '';
					}
					if (type === 2) {
						self.currentItem.confirmSheet = '';
					}
					if (type === 3) {
						self.currentItem.housePurchasingContract = '';
					}
					self.list({
						current: self.pageIndex,
						...self.searchData
					});
				});
			});



		},
		tabHandleClick({ index } = e) {
			console.log(this.activeIndex);
			this.type = this.activeIndex;
			this.list();
		},
		handleClick(data) {
			let self = this;
			switch (data.event.type) {
				case 'upload':
					self.uploadDialogVisble = true;
					self.currentId = data.item.id;
					self.fileUrl = [];
					self.currentItem = data.item;
					if (self.currentItem.demolitionAgreement === '0') {
						self.currentItem.demolitionAgreement = '';
					}
					if (self.currentItem.confirmSheet === '0') {
						self.currentItem.confirmSheet = '';
					}
					if (self.currentItem.housePurchasingContract === '0') {
						self.currentItem.housePurchasingContract = '';
					}
					break;
				case 'delete':
					this.$confirm('确定要删除这条数据吗?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						deleteById(data.item.id, self.type).then(ret => {
              self.$utils.notify('操作成功');
              if (data.item.confirm) {
                self.onSearch();
              } else {
                self.list({
                  batchNo: self.batchNo,
                  confirm: 0
                }, true);
              }
            });
					});
					break;
        case 'view':
          self.showDrawer = true
          break;
			}
		},
		list(params, isTemp) {
			let self = this;
			if (isTemp) {
				this.visble = true;
			}
			params = params || {};
			self.pageIndex = params.current || 1;
			houseList({ ...params, type: this.type, size: isTemp ? 10 : this.size }).then(ret => {
				if (!isTemp) {
					self.tableData = ret;
				} else {
					self.tempTableData = ret;
				}
			});
    },
    async batchDownload() {
      let self = this;
      if (this.selectedIds.length === 0) {
        self.$utils.notify('请选择需要下载的表格数据', 'warning');
        return;
      }
      let ret = await createDownLoadTask({ids: this.selectedIds});
      downLoadExcelBatchByType(ret, this.type);
    },
    batchDownloadAll() {
      downLoadExcelBatchByType("all", this.type);
    },
    selectionChange(e) {
      let selectedIds = [];
      e.forEach(it => {
        selectedIds.push(it.id);
      });
      this.selectedIds = this.selectedIds.concat(selectedIds);
    },
    navToHistory() {
      uni.navigateTo({
        url: '/house/upload/history?type=' + this.type
			});
		},
		tempPageChange(e, size) {
			this.list(
				{
					current: e,
					...this.searchData
				},
				true
			);
		},

		pageChange(e, size) {
			this.size = size || this.size;
			this.list({
				current: e,
				...this.searchData
			});
		},
		onSearch(e) {
			if (e) {
        this.searchData = e;
        if (e.startTimes && e.startTimes.length > 1) {
          this.searchData.startTime = e.startTimes[0];
          this.searchData.endTime = e.startTimes[1];
        }
        if (e.endTimes && e.endTimes.length > 1) {
          this.searchData.startTime2 = e.endTimes[0];
          this.searchData.endTime2 = e.endTimes[1];
        }
      }
			this.list({
				current: 1,
				...this.searchData
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.tabs-box {
	background-color: #fff;
}

.btns-box {
	padding: 0 16px;
	margin-bottom: -5px;
	border-radius: 5px;
	background-color: #fff;
	// height: 50px;
	width: 100%;
	// border-bottom: 1px solid #ccc;

	.btns {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: flex-end;
	}

	.upload-btn {
		margin: 0 10px;
		width: 80px;
		height: 28px;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 3px;
		font-size: 12px;
		// background-color: #409eff;
		border: 1px solid #ccc;
	}
}

.upload-box {
	padding: 0 32px;
	.upload-item {
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 10px;

		label {
			width: 100px;
			text-align: right;
			display: inline-block;
		}
	}
}
</style>
